/*
 *  soapUI, copyright (C) 2006 eviware.com 
 *
 *  soapUI is free software; you can redistribute it and/or modify it under the 
 *  terms of the GNU Lesser General Public License as published by the Free Software Foundation; 
 *  either version 2.1 of the License, or (at your option) any later version.
 *
 *  soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *  See the GNU Lesser General Public License for more details at gnu.org.
 */

package at.ac.tuwien.infosys.dsg.daios.wsdl.parser.soapui;

import java.io.File;

public class Tools
{
	/**
	 * Joins a relative url to a base url.. needs improvements..
	 */
	
	public static String joinRelativeUrl( String baseUrl, String url )
	{
	   boolean isFile = baseUrl.startsWith("file:");
	   
		int ix = baseUrl.lastIndexOf( '\\' );
		if( ix == -1 ) ix = baseUrl.lastIndexOf( '/' );
		
		// remove leader "./"
		while( url.startsWith( ".\\" ) || url.startsWith( "./" ))
			url = url.substring( 2 );
		
		// remove leading "../"
		while( url.startsWith( "../" ) || url.startsWith( "..\\" ))
		{
			int ix2 = baseUrl.lastIndexOf( '\\', ix-1 );
			if( ix2 == -1 )
				ix2 = baseUrl.lastIndexOf( '/', ix-1 );
			if( ix2 == -1 )
				break;
			
			baseUrl = baseUrl.substring( 0, ix2+1 );
			ix = ix2;
			
			url = url.substring( 3 );
		}
		
		//	remove "/./"
		while( url.indexOf( "/./" ) != -1 || url.indexOf( "\\.\\") != -1 )
		{
			int ix2 = url.indexOf( "/./");
			if( ix2 == -1 )
				ix2 = url.indexOf( "\\.\\" );
			
			url = url.substring( 0, ix2 ) + url.substring( ix2+2 );
		}
		
		//	remove "/../"
		while( url.indexOf( "/../" ) != -1 || url.indexOf( "\\..\\") != -1 )
		{
			int ix2 = -1;
			
			int ix3 = url.indexOf( "/../");
			if( ix3 == -1 )
			{
				ix3 = url.indexOf( "\\..\\" );
				ix2 = url.lastIndexOf( '\\', ix3-1 ); 
			}
			else
			{
				ix2 = url.lastIndexOf( '/', ix3-1 ); 
			}

			if( ix2 == -1 )
				break;
			
			url = url.substring( 0, ix2 ) + url.substring( ix3+3 );
		}
		
		String result = baseUrl.substring( 0, ix+1 ) + url;
		if( isFile )
			result = result.replace( '/', File.separatorChar );
		
		return result;
	}

	
}
